import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {AtSearchBar, AtIcon} from 'taro-ui'
import {ScrollView, View} from '@tarojs/components'
import {HotKey, Good, CityLocation} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {BANNER_SEARCH_TYPE, HOT_KEY, SCAN_BIND_SELLER, UPDATE_USER_SHARE_DATE} from '../../constants/api'
import {autoLocation, setCity} from '../../actions/location'
import {platform} from '../../utils/platform-settting.service'
import {getTempSellerId, vcmonitor, clearSearch as clearSearchFunc} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {user} from "../../utils/user.service";
import fetchNewGoodsList from "../../utils/fetchNewGoodsList";
import Category from "../../pages/index/template/regionalCategory/component/category";
import GoodsBigImgList from "../../components/goods-big-img-list/goods-big-img-list";
import Share from "../../components/share/share";
import './search.scss'

interface stateType {
  tabs: any
  tabId: number
  isUser: boolean
  hotKey: HotKey[]
  searchResult: Good[]
  linkUri: string
  searchText: string
  labelText: string
  loadMoreStatus: "more" | "loading" | "noMore"
}

type PageStateProps = {
  location: CityLocation
}

type PageDispatchProps = {
  setCity: (city: CityLocation) => void
  autoLocation: (city: CityLocation) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Search {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({
  setCity(city) {
    dispatch(setCity(city))
  },
  autoLocation(city) {
    dispatch(autoLocation(city))
  }
}))

class Search extends Component {
  state: stateType = {
    hotKey: [],
    searchResult: [],
    linkUri: '',
    searchText: '',
    labelText: '',
    tabs: [
      {id: 0, name: '佣金', key: 'commission'},
      {id: 1, name: '最新', key: 'newest'},
      {id: 2, name: '销量', key: 'sales'},
      {id: 3, name: '价格', key: 'price'}
    ],
    tabId: -1,
    isUser: true,
    loadMoreStatus: 'more'
  }
  page = 1
  total = 0
  length = 10
  canMore = false

  searchConfirm() {
    this.page = 1
    this.search(this.page)
  }

  async onPullDownRefresh() {
    this.page = 1
    await this.search(1)
    Taro.stopPullDownRefresh()
  }

  async componentDidShow() {
    vcmonitor(this)
    let isUser = true
    const isLogin = await user.checkLogin();
    if (process.env.DISTINGUISH_IDENTITY && isLogin) {
      const userIdentity = await user.getUserData()
      if (userIdentity && userIdentity.isSeller) {
        isUser = false
      }
    }
    this.setState({isUser})
    let tabs = [{id: 1, name: '最新', key: 'newest'}, {id: 3, name: '价格', key: 'price'}]
    if (isUser) { // 用户
      if (platform.info.is_show_sales_volume) {
        tabs = [{id: 1, name: '最新', key: 'newest'}, {id: 2, name: '销量', key: 'sales'}, {
          id: 3,
          name: '价格',
          key: 'price'
        }]
      }
      this.setState({
        tabs
      })
    } else { // 达人
      tabs = [{id: 0, name: '佣金', key: 'commission'}, {id: 1, name: '最新', key: 'newest'}, {
        id: 3,
        name: '价格',
        key: 'price'
      }]
      if (platform.info.is_show_sales_volume) {
        tabs = [{id: 0, name: '佣金', key: 'commission'}, {id: 1, name: '最新', key: 'newest'}, {
          id: 2,
          name: '销量',
          key: 'sales'
        }, {id: 3, name: '价格', key: 'price'}]
      }
      this.setState({
        tabs
      })
    }
  }

  searchType

  async UNSAFE_componentWillMount() {
    const fromDetail = Taro.getStorageSync("fromDetail"); // 是否详情页过来
    const data = await http.post(BANNER_SEARCH_TYPE, {})
    this.searchType = +data.head_type.banner_search_type
    if (process.env.TARO_ENV !== 'h5') {
      await Taro.hideShareMenu()
    }
    const setting = await platform.getSetting();
    const hotKeyServerData = await http.post<HotKey[]>(HOT_KEY, {})
    if (!hotKeyServerData) {
      return false
    }
    if (Taro.getCurrentInstance().router.params.key) {
      this.setState({hotKey: hotKeyServerData, searchText: Taro.getCurrentInstance().router.params.key}, async () => {
        await this.search(this.page)
      })
    } else {
      const label = Taro.getCurrentInstance().router.params.label || ''
      if (label) {
        const orderTypeName = Taro.getCurrentInstance().router.params.orderType || ''
        const orderByName = Taro.getCurrentInstance().router.params.orderBy || 'asc'
        let orderType = -1
        if (orderTypeName) {
          switch (orderTypeName) {
            case '佣金':
              orderType = 0
              break
            case '最新':
              orderType = 1
              break
            case '销量':
              orderType = 2
              break
            case '价格':
              orderType = 3
              break
            default:
              orderType = -1
          }
        }
        if (orderByName) {
          if (orderByName === "desc") {
            this.topOrBottom = 0
          } else {
            this.topOrBottom = 1
          }
        }
        this.setState({tabId: orderType})
        Taro.setNavigationBarTitle({
          title: label
        })
        const shareParams = await user.getSellerParams(getTempSellerId(this))
        let mpkey = ''
        const uInfo = Taro.getStorageSync('user') || ''
        if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
          mpkey = uInfo.mpkey
        }
        let link = '/common/search/search?label=' + encodeURIComponent(label) + '&' + shareParams + '&mpkey=' + mpkey
        if (process.env.TARO_ENV === 'h5') {
          link = window.location.origin + link
          const shareData = {
            title: label,
            desc: '欢乐加倍 从来不贵 超多3折遛娃优惠商品 快乐童乐从这开始',
            link,
            imgUrl: platform.info.platformLogo
          }
          h5Wx.share(shareData)
        } else {
          link += `&sKey=${Taro.getStorageSync('sKey' || '')}`
          Taro.showShareMenu({
            showShareItems: ['shareAppMessage']
          });
        }
        this.setState({linkUri: link, hotKey: hotKeyServerData, labelText: label}, async () => {
          await this.search(this.page)
          if (this.state.searchResult && this.state.searchResult.length > 0) {
            if (process.env.TARO_ENV === 'h5') {
              const shareData = {
                title: label,
                desc: '欢乐加倍 从来不贵 超多3折遛娃优惠商品 快乐童乐从这开始',
                link,
                imgUrl: this.state.searchResult[0]['img'] || platform.info.platformLogo
              }
              h5Wx.share(shareData)
            } else {
              Taro.showShareMenu({
                showShareItems: ['shareAppMessage']
              });
            }
          }
        })
      } else {
        if (setting && setting.platformName) {
          Taro.setNavigationBarTitle({
            title: setting.platformName
          })
        }
        this.setState({hotKey: hotKeyServerData})
      }
    }

    if (process.env.TARO_ENV === 'h5') {
      if (!!fromDetail) {
        Taro.showLoading({title: '加载中...'})
        const searchText = fromDetail.split("_")[1];
        const categoryListCatch = Taro.getStorageSync("categoryList");
        const pageScrollTop = Taro.getStorageSync("pageScrollTop");
        const canPageScroll = Taro.getStorageSync("canPageScroll")
        const searchResult = !!categoryListCatch ? JSON.parse(categoryListCatch) : [];
        this.canMore = canPageScroll;
        this.setState({searchText, searchResult}, () => {
          Taro.removeStorageSync("fromDetail");

          if (pageScrollTop !== "" && pageScrollTop !== null && pageScrollTop !== undefined) {
            const scrollTop = parseInt(pageScrollTop);
            if (scrollTop > 0) {
              document.querySelector(".taro-tabbar__panel").scrollTop = scrollTop; // 设置滚动条位置
              Taro.removeStorageSync("pageScrollTop");
              Taro.removeStorageSync("canPageScroll");
            }
          }
          setTimeout(() => {
            Taro.hideLoading()
          }, 100)
        })
      }
    }
    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds});
    }
  }

  async onReachBottom() {
    if (this.canMore) {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      await this.search(this.page)
    }
  }

  handlePageScroll = () => {
    const tempCanMore = this.canMore;
    const pageScrollTop = document.querySelector(".taro-tabbar__panel").scrollTop;
    Taro.setStorageSync("pageScrollTop", pageScrollTop); // 保留滚动条位置
    Taro.setStorageSync("canPageScroll", tempCanMore); // 保留触底翻页状态
  }

  async search(page) {
    this.isSearch = true
    Taro.showLoading({title: '加载中...'})
    const result = await this.getSearchData(page);
    Taro.hideLoading()
    if (result && result.length > 0) {
      const ret = [];
      for (let i = 0, len = result.length; i < len; i++) {
        const obj = {
          ...result[i],
          commission_price: result[i].commission || "",
          salesVolume: result[i].sales_volume,
        }
        ret.push(obj);
      }
      if (page === 1) {
        this.setState({searchResult: ret})
      } else if (page > 1) {
        const oldData = this.state.searchResult;
        this.setState({searchResult: [...oldData, ...ret]})
      }
    } else {
      this.canMore = false
      Taro.showToast({
        title: '没有更多数据了',
        icon: 'none'
      })
    }
  }

  async getSearchData(page) {
    const orderBy = this.topOrBottom ? "asc" : "desc"
    if (typeof page != "number") {
      page = this.page + 1
    }
    const {searchText, labelText} = this.state
    if (searchText || labelText) {
      const data = {
        p: page,
        draw: page,
        s: this.length,
        orderType: this.state.tabId,
        orderBy: orderBy,
        areaId: this.props.location.region_id
      }
      if (searchText) {
        data['k'] = searchText
      }
      if (labelText) {
        data['label'] = labelText
      }
      const result = await fetchNewGoodsList.getGoodsList({
        module_type: "3",
        page: this.page,
        length: this.length,
        order_rule: this.state.tabId,
        order_by: orderBy,
        key_word: searchText,
        label: labelText
      });
      if (!result) {
        return false;
      }
      if (result.length < 10) {
        this.canMore = false
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.canMore = true
        this.setState({loadMoreStatus: 'more'})
      }
      return result
    } else {
      Taro.showToast({
        title: '搜索词不能为空',
        icon: 'none'
      })
    }
    return false
  }

  input(value) {
    if (value) {
      this.setState({searchText: value})
    } else {
      clearSearchFunc();
    }
  }

  hotKeyClick(name) {
    if (name) {
      this.setState({searchText: name, labelText: ''}, () => {
        this.search(1);
      })
    }
  }

  clearSearch() {
    this.isSearch = false
    this.canMore = false
    this.setState({searchText: '', searchResult: []})
  }

  tabClick(tabId) {
    if (tabId === 1 || tabId === 0) {
      this.topOrBottom = 0
    } else {
      this.topOrBottom = this.topOrBottom === 0 ? 1 : 0
    }
    this.setState({tabId, loadMoreStatus: 'loading', searchResult: []}, async () => {
      this.page = 1
      await this.search(this.page)
    })
  }

  topOrBottom = 1

  keyChange(topOrBottom, tabId) {
    this.topOrBottom = topOrBottom
    this.setState({tabId})
    this.searchConfirm()
  }

  jump(url) {
    Taro.navigateTo({
      url
    })
  }

  isSearch = false

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: '',
      path: this.state.linkUri
    }
  }

  render() {
    const {isUser, hotKey, searchResult, searchText, labelText, loadMoreStatus, tabs, tabId, linkUri} = this.state
    return (
      <View className='search-root'>
        <GzhAuth />
        <View className='search-top'>
          {!labelText && !this.searchType &&
          <AtSearchBar onConfirm={this.searchConfirm.bind(this)}
            onClear={this.clearSearch.bind(this)} onActionClick={this.searchConfirm.bind(this)}
            value={searchText} onChange={this.input.bind(this)} placeholder='搜索关键词'
          />}
          {searchText && this.isSearch && <View className='tabs'>
            <ScrollView scrollX enable-flex className='subNav'>
              <View className='nav-box'>
                {tabs.length > 0 && tabs.map(item =>
                  <View key={item.id} onClick={this.tabClick.bind(this, item.id)}
                    className={`nav-item ${tabId === item.id ? 'active' : ''}`}
                  >
                    <View className='tabs-cat'>
                      <View className='text-name'>
                        {item.name}
                      </View>
                      {(item.key === 'sales' || item.key === 'price') && <View className='topOrBottom'>
                        <AtIcon className={`${this.topOrBottom === 1 ? 'tab-active' : 'tab-in-active'}`}
                          prefixClass='car'
                          onClick={this.keyChange.bind(this, 1, item.id)} value='iconshangsanjiaoxing' size='12'
                        />
                        <AtIcon className={`${this.topOrBottom === 0 ? 'tab-active' : 'tab-in-active'}`}
                          prefixClass='car'
                          onClick={this.keyChange.bind(this, 0, item.id)} value='iconxiasanjiaoxing' size='12'
                        />
                      </View>}
                    </View>
                  </View>
                )}
              </View>
            </ScrollView>
          </View>}
        </View>
        {searchResult.length === 0 && loadMoreStatus !== 'loading' && <View className='hot-key'>
          <View className='title'>热门搜索：</View>
          <View className='content'>
            {hotKey.map((item, index) => <View className='tag-box' key={index}
              onClick={this.hotKeyClick.bind(this, item.name)}
            ><View
              className='tag'
            >{item.name}</View></View>)}
          </View>
        </View>}
        {searchResult.length > 0 && !labelText && <View style='height: 12.5px;' />}
        {searchResult.length > 0 && !labelText &&
        <Category data={searchResult} isUser={isUser} fromWhere={`search_${searchText}`}
          handlePageScroll={this.handlePageScroll}
        />}
        {searchResult.length > 0 && labelText &&
        <View className='goods-ig-img-list-search'><GoodsBigImgList data={searchResult} isUser={isUser} /></View>}
        {linkUri && <Share isUser={isUser} linkUri={linkUri} />}
      </View>
    )
  }
}

export default Search as ComponentClass<PageOwnProps, PageState>
